import 'package:flutter/material.dart';
import 'package:sweet_app/bloc/application_bloc.dart';
import 'package:sweet_app/bloc/bloc_provider.dart';
import 'package:sweet_app/bloc/search_bloc.dart';
import 'package:sweet_app/model/message_model.dart';
import 'package:sweet_app/pages/add/add_friend_page.dart';
import 'package:sweet_app/pages/home_page.dart';
import 'package:sweet_app/pages/login/login.dart';
import 'package:sweet_app/pages/register/register_page.dart';
import 'package:uuid/uuid.dart';

void main() {
  runApp(BlocProvider(child: MyApp(), bloc: ApplicationBloc()));
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        primaryColor: Colors.blueAccent,
      ),
      routes: {
        "/addFriend": (context) => StackPage(child: AddFriendPage()),
        "/login": (context) => LoginPage(),
        "/register": (context) => RegisterPage()
      },
      home: StackPage(child: HomePage()),
    );
  }
}

class StackPage extends StatelessWidget {
  final Widget child;

  const StackPage({@required this.child});

  @override
  Widget build(BuildContext context) {
    final ApplicationBloc appBloc = BlocProvider.of<ApplicationBloc>(context);
    return Material(
      child: Stack(
        children: <Widget>[
          child,
          Positioned(
              top: 30.0,
              left: 10.0,
              right: 10.0,
              child: StreamBuilder<NotifyMessage>(
                  builder: (context, snapshot) {
                    if (snapshot.hasData) {
                      return Offstage(
                        offstage: snapshot.data == null,
                        child: NotifyWidget(
                            onTap: () => appBloc.removeNotify(),
                            name: snapshot.data.title,
                            content: snapshot.data.content),
                      );
                    } else {
                      return Container(width: 0.0, height: 0.0);
                    }
                  },
                  stream: appBloc.notifyMessageStream)),
        ],
      ),
    );
  }
}

class NotifyWidget extends StatelessWidget {
  final String name;
  final String content;
  final VoidCallback onTap;

  const NotifyWidget({this.name, this.content, this.onTap});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(10.0)),
            color: Colors.white),
        child: ListTile(
          onTap: onTap,
          leading: Icon(Icons.new_releases, color: Colors.deepOrangeAccent),
          title: Text(name, overflow: TextOverflow.ellipsis),
          subtitle: Text(content, overflow: TextOverflow.ellipsis),
        ));
  }
}
